// LGUIButton.cpp: implementation of the LGUIButton class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "LAMEBuffer.h"
#include "LGUIButton.h"
#include "LGUIContainer.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

LGUIButton::LGUIButton(const TCHAR *_text, int id, int _x, int _y, int _w, int _h, int _style, LAMEBitmap *_bmp) : LGUIWindow(_x,_y,_w,_h)
{
	pressed=down=false;
	ID=id;
	text=_text;
	style=_style;
	bmp=_bmp;
}

LGUIButton::~LGUIButton()
{

}



void LGUIButton::draw(int xoff, int yoff)
{
	if (isDirty)
	{
		int color=pressed ? COLOR(0x80c0ef) : COLOR(0xa0c0f0);
		buffer.rectFillFaded(x+xoff,y+yoff,x+xoff+w,y+yoff+h,color,pressed?whitenColor(color):darkenColor(color));
		buffer.rect(x+xoff,y+yoff,x+xoff+w,y+yoff+h,pressed ? COLOR(0x0) : COLOR(0x203050));
		int offset=pressed ? 1 : 0;

		if (text)
			buffer.drawTextShadowCenter(text,x+xoff+w/2-1+offset,y+yoff+h/2+offset);
		if (bmp)
			bmp->blitToCoordCenter(buffer,x+xoff+w/2+offset,y+yoff+h/2+offset,sprite_blit_pink);

		short16 col=pressed ? COLOR(0) : COLOR(0xb0d0ff);
		buffer.hLine(x+xoff,y+yoff+offset,x+xoff+w,col);
		buffer.vLine(x+xoff+offset,y+yoff+1,y+yoff+h,col);
		buffer.putPixel(x+xoff,y+yoff,pressed ? COLOR(0) : COLOR(0xFFFFFF));
		buffer.putPixel(x+xoff+w,y+yoff+h,COLOR(0));

		LRect dirty = *this;
		dirty.x+=xoff;
		dirty.y+=yoff;
		dirty.w++;
		dirty.h++;
		buffer.addDirtyRect(dirty);

		isDirty=false;
	}
}


void LGUIButton::penDown(int px, int py)
{
	if (isInside(px,py))
	{
		if (style==0)
		{
			lastPressed=true;
			pressed=true;
			down=true;
		}
		else
		{
			down=!down;
			pressed=down;
			if (parent!=0)
				parent->deliverMessage(LGUIMessage(MSG_BUTTONPRESSED,ID,down?1:0));
		}
		redraw();
	}
}


void LGUIButton::penMove(int px, int py, bool p)
{
	if (style==0)
	{
		if (!p || !down) return;
		pressed=isInside(px,py);
		if (lastPressed != pressed)
			redraw();
		lastPressed=pressed;
	}
}

void LGUIButton::penUp(int px, int py)
{
	if (style==0) 
	{
		if (isInside(px,py))
		{
			if (down && parent!=0)
				parent->deliverMessage(LGUIMessage(MSG_BUTTONPRESSED,ID));
			redraw();
		}
		pressed=false;
		down=false;
	}
}